import axios, { type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
import { raTokenFun }from '@/utils/secret';
import { useUserStore } from '@/store/user';

axios.defaults.withCredentials = false;
const OtherServer: AxiosInstance = axios.create({
  timeout: 120000
});

OtherServer.interceptors.request.use(request => requestIntercept(request), error => errorIntercept(error));
OtherServer.interceptors.response.use((response) => responseIntercept(response), error => errorIntercept(error));

//请求拦截
const requestIntercept = (request: InternalAxiosRequestConfig<any>) => {
  request.headers!['Content-Type'] ='application/x-www-form-urlencoded';
//   request.headers!['Content-Type'] ='application/json';
 if(request.method !== 'get') {
    request.headers!['X-Ra-Token'] = raTokenFun();
  }

  const userStore = useUserStore();
  if(userStore.otherServerToken !== '') {
    request.headers!['Authorization'] = userStore.otherServerToken;
  }

  return request;
}

const responseIntercept = (response: AxiosResponse) => {
  // console.log('response', response)
  if(response.request.responseType === 'blob') {
    return Promise.resolve(response);
  } else {
    return Promise.resolve(response.data);
  }
  
}
//错误拦截
const errorIntercept = (error: any) => {
  console.log("error___", error);
}


export const customRequest = (url: string, method: string, data?: any) => {
  const config: any = {
    url,
    method: method.toLowerCase()
  };
  
  if (method.toUpperCase() === 'GET') {
    config.params = data;
  } else {
    config.data = data;
  }
  
  return OtherServer(config);
};